package gui.storageunit;

import gui.common.*;
import hit.core.HomeInventoryTracker;
import hit.core.StorageUnit;
import hit.core.TreeFacade;
import hit.dao.DataAccessObject;
import hit.dao.FactoryReference;

/**
 * Controller class for the add storage unit view.
 */
public class AddStorageUnitController extends Controller implements
		IAddStorageUnitController {
	
	private TreeFacade facade;
	
	/**
	 * Constructor.
	 * 
	 * @param view Reference to add storage unit view
	 */
	public AddStorageUnitController(IView view) {
		super(view);
		
		facade = HomeInventoryTracker.Instance().GetTreeFacade();
		
		construct();
	}

	//
	// Controller overrides
	//
	
	/**
	 * Returns a reference to the view for this controller.
	 * 
	 * {@pre None}
	 * 
	 * {@post Returns a reference to the view for this controller.}
	 */
	@Override
	protected IAddStorageUnitView getView() {
		return (IAddStorageUnitView)super.getView();
	}

	/**
	 * Sets the enable/disable state of all components in the controller's view.
	 * A component should be enabled only if the user is currently
	 * allowed to interact with that component.
	 * 
	 * {@pre None}
	 * 
	 * {@post The enable/disable state of all components in the controller's view
	 * have been set appropriately.}
	 */
	@Override
	protected void enableComponents() {
		//check if the name is valid
		valuesChanged();
	}

	/**
	 * Loads data into the controller's view.
	 * 
	 *  {@pre None}
	 *  
	 *  {@post The controller has loaded data into its view}
	 */
	@Override
	protected void loadValues() {
		//shouldn't be needed for this view
	}

	//
	// IAddStorageUnitController overrides
	//

	/**
	 * This method is called when any of the fields in the
	 * add storage unit view is changed by the user.
	 */
	@Override
	public void valuesChanged() {
		IAddStorageUnitView view = getView();
		String name = view.getStorageUnitName();
		
		//if the current name is valid, enable the add button
		StorageUnit unit = new StorageUnit(name);
		if (facade.CanAddStorageUnit(unit)) {
			view.enableOK(true);
		}
		else {
			view.enableOK(false);
		}
	}
	
	/**
	 * This method is called when the user clicks the "OK"
	 * button in the add storage unit view.
	 */
	@Override
	public void addStorageUnit() {
		String name = getView().getStorageUnitName();
		StorageUnit unit = facade.AddStorageUnit(name);
		
		DataAccessObject dao = FactoryReference.GetFactory().CreateDataAccessObject();
		
		dao.StartTransaction();
		
		int id = dao.GetStorageUnitDAO().Create(unit);
		unit.setId(id);
		
		dao.EndTransaction(true);
		
		dao.CloseConnection();
	}

}

